<template>
  <div class="role-permission-container">
    <el-card class="search-card">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="角色名称">
          <el-input v-model="formInline.roleName" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">查询</el-button>
          <el-button type="success" @click="dialogFormVisible = true" :icon="Plus">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="title">角色权限列表</span>
        </div>
      </template>
      <el-table 
        :data="tableData" 
        border 
        style="width: 100%" 
        :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
        v-loading="loading"
        row-key="id"
        stripe
        highlight-current-row
      >
        <el-table-column prop="id" type="index" label="角色编号" width="100" align="center" />
        <el-table-column prop="roleName" label="角色名称" width="200" align="center" />
        <el-table-column prop="permissionName" label="权限" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.state"
              :active-value="true"
              :inactive-value="false"
              @change="handleStateChange(scope.row)"
              active-text="启用"
              inactive-text="禁用"
              :loading="stateLoading === scope.row.id"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center">
          <template v-slot="scope">
            <el-button type="primary" size="small" @click="find(scope.row)" :icon="Edit">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)" :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="formInline.pageIndex"
          v-model:page-size="formInline.pageSize"
          :page-sizes="[3, 6, 7, 9]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagin.totaleCount"
        />
      </div>
    </el-card>

    <!-- 新增 -->
    <el-dialog v-model="dialogFormVisible" title="新增角色" width="500" center destroy-on-close>
      <el-form :model="form" :rules="rules" ref="addFormRef" label-position="right" :label-width="formLabelWidth">
        <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description" :label-width="formLabelWidth">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="选择权限" prop="permissionId" :label-width="formLabelWidth">
          <el-checkbox-group v-model="form.permissionId">
            <div class="checkbox-container">
              <el-checkbox name="type" v-for="a in Bind" :key="a.id" :value="a.id" border>
                {{ a.permissionName }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="add()">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog v-model="dialogFormVisible2" title="编辑角色" width="500" center destroy-on-close>
      <el-form :model="form2" :rules="rules" ref="editFormRef" label-position="right" :label-width="formLabelWidth">
        <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="form2.roleName" autocomplete="off" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description" :label-width="formLabelWidth">
          <el-input v-model="form2.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="选择权限" prop="permissionId" :label-width="formLabelWidth">
          <el-checkbox-group v-model="form2.permissionId">
            <div class="checkbox-container">
              <el-checkbox name="type" v-for="a in Bind" :key="a.id" :value="a.id" border>
                {{ a.permissionName }}
              </el-checkbox>
            </div>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取消</el-button>
          <el-button type="primary" @click="update()">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 删除确认对话框 -->
    <el-dialog v-model="deleteDialogVisible" title="提示" width="300px" center>
      <div class="delete-dialog-content">
        <el-icon class="delete-icon"><WarningFilled /></el-icon>
        <span>确定要删除角色 "{{ currentDeleteItem?.roleName }}" 吗？</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { onMounted, ref, watch } from 'vue';
import { reactive } from 'vue';
import { Search, Plus, Edit, Delete, WarningFilled } from '@element-plus/icons-vue';

import{getALLRole,getRole,addRole,updateRole,updateRoleState,deleteRole,getAll} from'@/HTTPS/server'

// 定义类型接口
interface RoleItem {
  id: number;
  roleName: string;
  description: string;
  permissionId: number[];
  permissionName: string;
  state: boolean;
}

interface PermissionItem {
  id: number;
  permissionName: string;
}

onMounted(()=>{
    show();
    bind();
})

const loading = ref(false);
const stateLoading = ref<number | null>(null);

const formInline = reactive({
  roleName: '',
  pageIndex: 1,
  pageSize: 3,
})

const onSubmit = () => {
  console.log('submit!');
  formInline.pageIndex = 1; // 重置页码
  show();
}

const pagin=ref({
    totaleCount:0,
    pageCount:0,
   
})

watch(formInline,()=>{
    show();
},{deep:true})

const tableData = ref<RoleItem[]>([])
const show=()=>{
   loading.value = true;
   getALLRole(formInline)
     .then(res=>{
       tableData.value=res.data.data.list;
       pagin.value.pageCount=res.data.data.pageCount;
       pagin.value.totaleCount=res.data.data.totaleCount;
     })
     .catch(error => {
       ElMessage.error('获取角色列表失败');
       console.error(error);
     })
     .finally(() => {
       loading.value = false;
     });
}

// 表单校验规则
const rules = {
  roleName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 100, message: '描述不能超过100个字符', trigger: 'blur' }
  ],
  permissionId: [
    { type: 'array', required: true, message: '请至少选择一个权限', trigger: 'change' }
  ]
};


//新增角色
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'
const addFormRef = ref(null);

const form = reactive<{
  roleName: string;
  description: string;
  permissionId: number[];
}>({
 "roleName": "",
  "description": "",
  "permissionId": []
})

//获取权限列表
const Bind = ref<PermissionItem[]>([])
const bind=()=>{
    getAll()
      .then(res=>{
        Bind.value=res.data.data;
      })
      .catch(error => {
        ElMessage.error('获取权限列表失败');
        console.error(error);
      });
}

const add=()=>{
    addRole(form)
      .then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.message);
            dialogFormVisible.value = false
            show();
            // 重置表单
            form.roleName = "";
            form.description = "";
            form.permissionId = [];
        }else{
            ElMessage.error(res.data.message);
        }
      })
      .catch(error => {
        ElMessage.error('新增角色失败');
        console.error(error);
      });
}

//编辑角色
const dialogFormVisible2 = ref(false)
const editFormRef = ref(null);

const form2 = reactive<{
  id: number;
  roleName: string;
  description: string;
  permissionId: number[];
}>({
    id:0,
    "roleName": "",
    "description": "",
    "permissionId": []
})

const find=(row: RoleItem)=>{
    console.log(row)
    
    dialogFormVisible2.value = true
    form2.id=row.id;
    form2.roleName=row.roleName;
    form2.description=row.description;
    form2.permissionId=row.permissionId;
    console.log(form2);
}

const update=()=>{
    updateRole(form2)
      .then(res=>{
        if(res.data.code==200){
            ElMessage.success(res.data.message);
            dialogFormVisible2.value = false
            show();
        }else{
            ElMessage.error(res.data.message);
        }
      })
      .catch(error => {
        ElMessage.error('更新角色失败');
        console.error(error);
      });
}

// 删除角色
const deleteDialogVisible = ref(false);
const currentDeleteItem = ref<RoleItem | null>(null);

const handleDelete = (row: RoleItem) => {
  deleteDialogVisible.value = true;
  currentDeleteItem.value = row;
};

const confirmDelete = () => {
  if (!currentDeleteItem.value) return;
  
  deleteRole({ id: currentDeleteItem.value.id })
    .then(res => {
      if (res.data.code == 200) {
        ElMessage.success('删除成功');
        deleteDialogVisible.value = false;
        show(); // 刷新列表
      } else {
        ElMessage.error(res.data.message || '删除失败');
      }
    })
    .catch(error => {
      ElMessage.error('删除角色失败');
      console.error(error);
    });
};

// 处理角色状态变更
const handleStateChange = (row: RoleItem) => {
  // 设置当前行的状态切换加载状态
  stateLoading.value = row.id;
  
  // 调用后端API更新角色状态
  updateRoleState({ 
    id: row.id, 
    state: row.state 
  })
  .then(res => {
    if(res.data.code == 200) {
      ElMessage.success(res.data.message || `${row.state ? '启用' : '禁用'}角色成功`);
    } else {
      // 如果失败，恢复原状态
      row.state = !row.state;
      ElMessage.error(res.data.message || '修改状态失败');
    }
  })
  .catch(error => {
    // 发生错误时，恢复原状态
    row.state = !row.state;
    ElMessage.error('修改角色状态失败');
    console.error(error);
  })
  .finally(() => {
    // 无论成功失败，都结束加载状态
    stateLoading.value = null;
  });
};

</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>

<style scoped>
.role-permission-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.checkbox-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-height: 200px;
  overflow-y: auto;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-checkbox.is-bordered+.el-checkbox.is-bordered) {
  margin-left: 0;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #f5f7fa;
}

.delete-dialog-content {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 16px 0;
}

.delete-icon {
  font-size: 24px;
  color: #f56c6c;
  margin-bottom: 10px;
}
</style>